package com.opengit;

import com.aspose.imaging.Image;
import com.aspose.imaging.fileformats.jpeg.JpegImage;
import com.aspose.imaging.fileformats.tiff.TiffFrame;
import com.aspose.imaging.fileformats.tiff.TiffImage;
import com.aspose.imaging.imageoptions.JpegOptions;
import com.aspose.imaging.imageoptions.TiffOptions;
import com.sun.media.jai.codec.*;

import javax.media.jai.JAI;
import javax.media.jai.PlanarImage;
import java.awt.image.BufferedImage;
import java.awt.image.renderable.ParameterBlock;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

/**
 * @Author: yxf
 * @version: 1.0
 * @Date: 2019/01/28 12:01
 * @Description:
 */
public class TiffConvert {
    private static SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    /**
     * 授权文件
     */
    private static final String STRING_LICENSE = "<License>\n" +
            "  <Data>\n" +
            "    <Products>\n" +
            "      <Product>Aspose.Total for Java</Product>\n" +
            "    </Products>\n" +
            "    <EditionType>Enterprise</EditionType>\n" +
            "    <SubscriptionExpiry>20991231</SubscriptionExpiry>\n" +
            "    <LicenseExpiry>20991231</LicenseExpiry>\n" +
            "    <SerialNumber>8bfe198c-7f0c-4ef8-8ff0-acc3237bf0d7</SerialNumber>\n" +
            "  </Data>\n" +
            "  <Signature>sNLLKGMUdF0r8O1kKilWAGdgfs2BvJb/2Xp8p5iuDVfZXmhppo+d0Ran1P9TKdjV4ABwAgKXxJ3jcQTqE/2IRfqwnPf8itN8aFZlV3TJPYeD3yWE7IT55Gz6EijUpC7aKeoohTb4w2fpox58wWoF3SNp6sK6jDfiAUGEHYJ9pjU=</Signature>\n" +
            "</License>";

    public static boolean checkLicenses() {
        boolean result = false;
        try {
            InputStream isImageing = new ByteArrayInputStream(STRING_LICENSE.getBytes());
            com.aspose.imaging.License licImageing = new com.aspose.imaging.License();
            licImageing.setLicense(isImageing);
            result = true;
            System.out.println("The license of imageing is valid！");
        } catch (Exception e) {
            System.out.println("The license of imageing is invalid！");
        }
        return result;
    }

    private static TIFFExports tiffExports = new TIFFExports();

    public static void main(String[] args) throws Exception {
        //checkLicenses();
        //testMuti2on2e();
        // jpg2tiff();
        testM();
        System.out.println("----------");
    }

    public static void testM(){
        long old = System.currentTimeMillis();
        System.out.println(" -- 开始时间：" + simpleDateFormat.format(old) + " 开始处理 -- ");

        List<String> bookFilePaths = new ArrayList<String>();
        for(int i=1;i<=100;i++) {
            // bookFilePaths.add(String.format("D:\\04jlrz\\%03d.jpg",i));
            // bookFilePaths.add("D:\\01.jpg");
            bookFilePaths.add("D:\\02.jpg");
        }
//        bookFilePaths.add("D:\\04jlrz\\001.jpg");
//        bookFilePaths.add("D:\\04jlrz\\002.jpg");
//        bookFilePaths.add("D:\\04jlrz\\003.jpg");
//        bookFilePaths.add("D:\\04jlrz\\004.jpg");
//        bookFilePaths.add("D:\\04jlrz\\005.jpg");
        String toPath ="d:\\";
        String distFileName="04jlrz.tiff";
        TiffExportJAI.many2one(bookFilePaths, toPath, distFileName);
        // many2one(bookFilePaths, toPath, distFileName);
        long now = System.currentTimeMillis();
        System.out.println(" -- 完成时间：" + simpleDateFormat.format(now) + " 共计耗时：" + ((now - old) / 1000.0) + " 秒。 -- ");
    }

    public static void testMuti2on2e() {
        long old = System.currentTimeMillis();
        System.out.println(" -- 开始时间：" + simpleDateFormat.format(old) + " -- 开始处理 -- ");

        com.aspose.imaging.ResolutionSetting resolution = new com.aspose.imaging.ResolutionSetting(200, 200);
        TiffOptions options = new TiffOptions(10);
        options.setResolutionSettings(resolution);

        List<TiffFrame> listTiffFrames = new ArrayList<TiffFrame>();
        TiffFrame tiffFrame = null;
        JpegImage jpegImage = null;
        TiffImage tiff = null;
        TiffFrame[] tiffFrames = new TiffFrame[100];
        for (int i = 0; i < 100; i++) {
            jpegImage = (JpegImage) Image.load(String.format("D:/04jlrz/%03d.jpg", i + 1));
            tiffFrames[i] = new TiffFrame(jpegImage, options);
            System.out.println(String.format("--- %03d -- 文件 %s", i, simpleDateFormat.format(System.currentTimeMillis())));
            // listTiffFrames.add(tiffFrame);
        }
        // TiffFrame[] arrT = new TiffFrame[listTiffFrames.size()];
        // tiff = new TiffImage(listTiffFrames.toArray(arrT));
        tiff = new TiffImage(tiffFrames);

        tiff.save("d:/" + getUUID() + ".tif", options);
        long now = System.currentTimeMillis();
        System.out.println(" -- 完成时间：" + simpleDateFormat.format(now) + " -- 共计耗时：" + ((now - old) / 1000.0) + " 秒。 -- ");
    }

    // aspose.imaging
    public static void testMuti2on2eddd() {
        com.aspose.imaging.ResolutionSetting resolution = new com.aspose.imaging.ResolutionSetting(200, 200);
        for (int j = 0; j < 15; j++) {
            TiffOptions options = new TiffOptions(j);
            options.setResolutionSettings(resolution);

            List<TiffFrame> listTiffFrames = new ArrayList<TiffFrame>();
            TiffFrame tiffFrame = null;
            JpegImage jpegImage = null;
            TiffImage tiff = null;
            TiffFrame[] tiffFrames = new TiffFrame[3];
            for (int i = 1; i < 4; i++) {
                jpegImage = (JpegImage) Image.load(String.format("d:/%02d.jpeg", i));
                tiffFrames[i - 1] = new TiffFrame(jpegImage, options);
                // listTiffFrames.add(tiffFrame);
            }
            // TiffFrame[] arrT = new TiffFrame[listTiffFrames.size()];
            // tiff = new TiffImage(listTiffFrames.toArray(arrT));
            tiff = new TiffImage(tiffFrames);

            tiff.save("d:/" + getUUID() + String.format("-%02d.tif", j), options);
        }

//        JpegImage jpegImage = (JpegImage) Image.load("d:/01.jpeg");
//        TiffFrame tiffFrame = new TiffFrame(jpegImage);
//        TiffImage tiff = new TiffImage(tiffFrame);
//        tiff.setActiveFrame(tiffFrame);
//        tiff.save("d:/zzz.tif", options);
    }

    public static void testOne2on2e() {
        String file = "d:/c2b2ceea-906e-4251-8a2e-c6ad2081b825.tif";
        com.aspose.imaging.ResolutionSetting resolution = new com.aspose.imaging.ResolutionSetting(200, 200);

        JpegOptions options = new JpegOptions();
        options.setResolutionSettings(resolution);
        options.setQuality(80);

        TiffImage tiff = (TiffImage) Image.load(file);
        try {
            TiffFrame[] frames = tiff.getFrames();
            for (int i = 0; i < frames.length; i++) {
                tiff.setActiveFrame(frames[i]);
                String jpegName = String.format("imaging_out%08d.jpg", i + 1);
                tiff.save("d:/" + jpegName, options);
            }
        } finally {
            tiff.dispose();
        }
    }

    public static void many2one(List<String> bookFilePaths, String toPath, String distFileName) {
        if (bookFilePaths != null && bookFilePaths.size() > 0) {
            File[] files = new File[bookFilePaths.size()];
            for (int i = 0; i < bookFilePaths.size(); i++) {
                files[i] = new File(bookFilePaths.get(i));
            }
            if (files != null && files.length > 0) {

                try {
                    ArrayList pages = new ArrayList(files.length - 1);
                    FileSeekableStream[] stream = new FileSeekableStream[files.length];
                    for (int i = 0; i < files.length; i++) {
                        stream[i] = new FileSeekableStream(files[i].getCanonicalPath());
                    }
                    ParameterBlock pb = (new ParameterBlock());
                    PlanarImage firstPage = JAI.create("stream", stream[0]);
                    for (int i = 1; i < files.length; i++) {
                        PlanarImage page = JAI.create("stream", stream[i]);
                        pages.add(page);
                    }
                    TIFFEncodeParam param = new TIFFEncodeParam();
                    param.setCompression(TIFFEncodeParam.COMPRESSION_JPEG_TTN2);
//					param.setCompression(TIFFEncodeParam.COMPRESSION_DEFLATE);
//					param.setDeflateLevel(9);
//					param.setWriteTiled(true);
//					param.setReverseFillOrder(true);
                    TIFFField[] extras = new TIFFField[4];
                    extras[0] = new TIFFField(262, TIFFField.TIFF_SHORT, 1, (Object) new short[]{6});
                    extras[1] = new TIFFField(282, TIFFField.TIFF_RATIONAL, 1, (Object) new long[][]{{(long) 200, 1}, {0, 0}});
                    extras[2] = new TIFFField(283, TIFFField.TIFF_RATIONAL, 1, (Object) new long[][]{{(long) 200, 1}, {0, 0}});
                    extras[3] = new TIFFField(258, TIFFField.TIFF_SHORT, 1, (Object) new char[]{8});
                    param.setExtraFields(extras);
                    param.setExtraImages(pages.iterator());
                    File f = new File(toPath);
                    if (!f.exists()) {
                        f.mkdirs();
                    }
                    OutputStream os = new FileOutputStream(toPath + File.separator + distFileName);
                    ImageEncoder enc = ImageCodec.createImageEncoder("tiff", os, param);
                    enc.encode(firstPage);
                    os.close();
                    System.out.println("over");
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

//    public static void jpg2tiff() {
//        String fileJpg = "D:\\01.jpg";
//        try {
//            Thumbnails.of(fileJpg)
//                    .size(3264, 2448)
//                    .outputFormat("tiff").outputQuality(0.25f)
//                    .toFile("d:\\01.tif");
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
//        System.out.println("jpg2tiff()");
//    }


    public static void testOne2one() {
        try {
            String filePath = "d:/01.jpeg";
            String fileOutPath = "d:/" + getUUID() + ".tif";
            tiffExports.OneToOne(fileOutPath, tiffExports.getBufferedImage(filePath));
            System.out.println("文件转换成功：" + fileOutPath);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void testMuti2one() {
        List<BufferedImage> bufferedImages = new ArrayList<BufferedImage>();
        try {
            String fileOutPath = "d:/" + getUUID() + ".tif";

            bufferedImages.add(tiffExports.getBufferedImage("d:/01.jpeg"));
            bufferedImages.add(tiffExports.getBufferedImage("d:/02.jpeg"));
            bufferedImages.add(tiffExports.getBufferedImage("d:/03.jpeg"));

//            for(int i=1;i<103;i++){
//                bufferedImages.add(tiffExports.getBufferedImage("D:\\04jlrz\\"+String.format("%03d",i)+".jpg"));
//            }

            tiffExports.MultipleToOne(fileOutPath, bufferedImages);

            System.out.println("多文件合并单tif转换成功：" + fileOutPath);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取随机UUID
     *
     * @return
     */
    public static String getUUID() {
        return UUID.randomUUID().toString();
    }
}
